package com.llw.notify;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import com.llw.notify.databinding.ActivityMainBinding;
import com.llw.notify.mail_sender.EmailType;
import com.llw.notify.mail_sender.ManageEmailActivity;
import com.llw.notify.notification.NotifyService;
import com.llw.notify.setting.ManageBlackValueActivity;
import com.llw.notify.setting.ImportMode;
import com.llw.notify.setting.SettingsManager;
import com.llw.notify.util.ToastLogger;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private final String TAG = getClass().getSimpleName();
    private static final int LISTENER_REQUEST_CODE = 9527;
    private static final int MANAGE_EMAIL_REQUEST_CODE = 1024;
    private ActivityMainBinding binding;

    private EmailType emailType;
    private boolean buttonStatus;

    private ToastLogger toastLogger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        emailType = EmailType.Receiver;

        toastLogger = new ToastLogger(MainActivity.this, TAG);

        initButtonListener();
        makeEmailAddressNonEditable();

        if (!SettingsManager.isEmailInfoSetup()) {
            disableButtons();
            return;
        }

        buttonStatus = true;
        updateEmailInfo();
        manageSyncButtonStatus();
        requestPermission();
    }

    private void disableButtons() {
        buttonStatus = false;
        binding.emailAddress.setText("请设置收发邮件的信息");
        binding.switchEmailType.setText("不可用");
        binding.switchEmailType.setEnabled(false);
        binding.startSync.setEnabled(false);
        binding.stopSync.setEnabled(false);
        binding.requestPermission.setEnabled(false);
        Log.i(TAG, "关闭按钮功能");
    }

    private void enableButtons() {
        updateEmailInfo();
        buttonStatus = true;
        binding.switchEmailType.setEnabled(true);
        manageSyncButtonStatus();
        binding.requestPermission.setEnabled(true);
        Log.i(TAG, "开启按钮功能");
    }

    private void manageSyncButtonStatus() {
        boolean sync = SettingsManager.isSyncSwitchOn();
        if (sync) {
            binding.startSync.setEnabled(false);
            binding.stopSync.setEnabled(true);
        }
        else {
            binding.startSync.setEnabled(true);
            binding.stopSync.setEnabled(false);
        }
    }

    private void initButtonListener() {
        binding.switchEmailType.setOnClickListener((view) -> {
            switchEmailType();
        });
        binding.manageEmail.setOnClickListener((view) -> {
            MainActivity.this.startActivityForResult(new Intent(MainActivity.this, ManageEmailActivity.class), MANAGE_EMAIL_REQUEST_CODE);
        });
        binding.addBlackWords.setOnClickListener((view) -> {
            updateBlackValue(ManageBlackValueActivity.WORD);
            toastLogger.s("屏蔽词管理");
        });
        binding.addBlackApps.setOnClickListener((view) -> {
            updateBlackValue(ManageBlackValueActivity.APP);
            toastLogger.s("屏蔽应用管理");
        });
        binding.importFromFile.setOnClickListener((view) -> {
            toastLogger.s(SettingsManager.importFromFile(ImportMode.Merge));
        });
        binding.exportToFile.setOnClickListener((view) -> {
            SettingsManager.exportToFile();
            toastLogger.s("已导出到文件中");
        });
        binding.startSync.setOnClickListener((view) -> {
            SettingsManager.switchSync();
            manageSyncButtonStatus();
            toastLogger.s("已 开启 同步");
        });
        binding.stopSync.setOnClickListener((view) -> {
            SettingsManager.switchSync();
            manageSyncButtonStatus();
            toastLogger.s("已 关闭 同步");
        });
        binding.requestPermission.setOnClickListener((view) -> {
            requestPermission();
        });
    }

    private void updateBlackValue(final String type) {
        Intent intent = new Intent(MainActivity.this, ManageBlackValueActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    private void makeEmailAddressNonEditable() {
        binding.emailAddress.setFocusable(false);
        binding.emailAddress.setFocusableInTouchMode(false);
        binding.emailAddress.setLongClickable(false);
    }

    private void switchEmailType() {
        switch (emailType) {
            case Receiver:
                emailType = EmailType.Sender;
                break;
            case Sender:
            default:
                emailType = EmailType.Receiver;
                break;
        }
        updateEmailInfo();
    }

    private void updateEmailInfo() {
        switch (emailType) {
            case Sender:
                binding.emailType.setText("发送方");
                String senderEmail = SettingsManager.getSenderEmail();
                binding.emailAddress.setText(senderEmail.isEmpty() ? "未设置" : senderEmail);
                binding.switchEmailType.setText("接收方");
                break;
            case Receiver:
            default:
                binding.emailType.setText("接收方");
                String receiverEmail = SettingsManager.getReceiverEmail();
                binding.emailAddress.setText(receiverEmail.isEmpty() ? "未设置" : receiverEmail);
                binding.switchEmailType.setText("发送方");
                break;
        }
    }

    /**
     * 切换通知监听器服务
     */
    public void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(getApplicationContext(), NotifyService.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(getApplicationContext(), NotifyService.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

        SettingsManager.initSettings();
        SettingsManager.startSync();
        manageSyncButtonStatus();
    }

    public void requestPermission() {
        if (!isNLServiceEnabled()) {
            toastLogger.s("即将跳转到权限授予页面\n请授予应用通知读取权限");
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivityForResult(intent, LISTENER_REQUEST_CODE);
        } else {
            toggleNotificationListenerService();
            toastLogger.s("通知服务已开启");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case LISTENER_REQUEST_CODE:
                if (isNLServiceEnabled()) {
                    toastLogger.s("通知侦听服务已开启");
                    toggleNotificationListenerService();
                } else {
                    toastLogger.s("通知侦听服务未开启");
                }
                break;
            case MANAGE_EMAIL_REQUEST_CODE:
                if (SettingsManager.isEmailInfoSetup() && !buttonStatus) {
                    requestPermission();
                    enableButtons();
                }
                break;
            default:
                Log.i(TAG, "未知的请求码");
                break;
        }
    }

    /**
     * 是否启用通知监听服务
     *
     * @return 是否已获取通知监听服务
     */
    public boolean isNLServiceEnabled() {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(getPackageName())) {
            Log.i(TAG, "通知侦听权限已获取");
            return true;
        }
        return false;
    }
}